//! Kafka消息定义
//! 
//! 定义在Kafka中传输的各种消息类型

use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use std::collections::HashMap;
use uuid::Uuid;

use crate::types::{SandboxId, Language, SandboxState, Priority};

/// 消息基础结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageHeader {
    /// 消息ID
    pub message_id: String,
    /// 消息类型
    pub message_type: String,
    /// 消息版本
    pub version: String,
    /// 发送时间
    pub timestamp: DateTime<Utc>,
    /// 发送者ID
    pub sender_id: String,
    /// 相关ID（用于消息链路跟踪）
    pub correlation_id: Option<String>,
}

impl MessageHeader {
    pub fn new(message_type: &str, sender_id: &str) -> Self {
        Self {
            message_id: Uuid::new_v4().to_string(),
            message_type: message_type.to_string(),
            version: "1.0".to_string(),
            timestamp: Utc::now(),
            sender_id: sender_id.to_string(),
            correlation_id: None,
        }
    }
    
    pub fn with_correlation_id(mut self, correlation_id: String) -> Self {
        self.correlation_id = Some(correlation_id);
        self
    }
}

/// 沙箱事件消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxEventMessage {
    /// 消息头
    pub header: MessageHeader,
    /// 沙箱ID
    pub sandbox_id: SandboxId,
    /// 事件类型
    pub event_type: SandboxEventType,
    /// 沙箱状态
    pub sandbox_state: SandboxState,
    /// 语言类型
    pub language: Language,
    /// 额外数据
    pub metadata: HashMap<String, serde_json::Value>,
}

/// 沙箱事件类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SandboxEventType {
    /// 沙箱创建
    Created,
    /// 沙箱启动
    Started,
    /// 沙箱停止
    Stopped,
    /// 沙箱销毁
    Destroyed,
    /// 状态变更
    StateChanged,
    /// 执行开始
    ExecutionStarted,
    /// 执行完成
    ExecutionCompleted,
    /// 执行失败
    ExecutionFailed,
    /// 健康检查失败
    HealthCheckFailed,
}

/// 执行任务消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionTaskMessage {
    /// 消息头
    pub header: MessageHeader,
    /// 任务ID
    pub task_id: String,
    /// 沙箱ID（可选，如果未指定则需要分配）
    pub sandbox_id: Option<SandboxId>,
    /// 执行请求
    pub execution_request: ExecutionRequest,
    /// 优先级
    pub priority: Priority,
    /// 超时时间（毫秒）
    pub timeout_ms: u64,
    /// 重试次数
    pub retry_count: u8,
    /// 最大重试次数
    pub max_retries: u8,
}

/// 执行请求（简化版本用于消息队列）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionRequest {
    /// 源代码
    pub source_code: String,
    /// 编程语言
    pub language: Language,
    /// 入口点
    pub entry_point: String,
    /// 环境变量
    pub env_vars: HashMap<String, String>,
    /// 标准输入
    pub stdin: String,
}

/// 系统指标消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemMetricsMessage {
    /// 消息头
    pub header: MessageHeader,
    /// 指标类型
    pub metrics_type: MetricsType,
    /// 指标数据
    pub metrics: HashMap<String, f64>,
    /// 标签
    pub labels: HashMap<String, String>,
}

/// 指标类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MetricsType {
    /// 系统资源使用
    SystemResource,
    /// 沙箱池统计
    PoolStatistics,
    /// 执行性能
    ExecutionPerformance,
    /// 网络流量
    NetworkTraffic,
    /// 自定义指标
    Custom,
}

/// 错误报告消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorReportMessage {
    /// 消息头
    pub header: MessageHeader,
    /// 错误级别
    pub level: ErrorLevel,
    /// 错误代码
    pub error_code: String,
    /// 错误消息
    pub error_message: String,
    /// 错误详情
    pub error_details: Option<String>,
    /// 相关的沙箱ID
    pub sandbox_id: Option<SandboxId>,
    /// 堆栈跟踪
    pub stack_trace: Option<String>,
    /// 上下文信息
    pub context: HashMap<String, serde_json::Value>,
}

/// 错误级别
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorLevel {
    /// 调试信息
    Debug,
    /// 一般信息
    Info,
    /// 警告
    Warning,
    /// 错误
    Error,
    /// 致命错误
    Fatal,
}

/// 健康检查消息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckMessage {
    /// 消息头
    pub header: MessageHeader,
    /// 组件名称
    pub component: String,
    /// 健康状态
    pub status: HealthStatus,
    /// 检查结果详情
    pub details: HashMap<String, serde_json::Value>,
    /// 响应时间（毫秒）
    pub response_time_ms: u64,
}

/// 健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HealthStatus {
    /// 健康
    Healthy,
    /// 降级服务
    Degraded,
    /// 不健康
    Unhealthy,
    /// 未知状态
    Unknown,
}

/// 通用的Kafka消息包装器
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum KafkaMessage {
    SandboxEvent(SandboxEventMessage),
    ExecutionTask(ExecutionTaskMessage),
    SystemMetrics(SystemMetricsMessage),
    ErrorReport(ErrorReportMessage),
    HealthCheck(HealthCheckMessage),
}

impl KafkaMessage {
    /// 获取消息头
    pub fn header(&self) -> &MessageHeader {
        match self {
            KafkaMessage::SandboxEvent(msg) => &msg.header,
            KafkaMessage::ExecutionTask(msg) => &msg.header,
            KafkaMessage::SystemMetrics(msg) => &msg.header,
            KafkaMessage::ErrorReport(msg) => &msg.header,
            KafkaMessage::HealthCheck(msg) => &msg.header,
        }
    }
    
    /// 获取消息类型字符串
    pub fn message_type(&self) -> &str {
        &self.header().message_type
    }
    
    /// 序列化为JSON字符串
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }
    
    /// 从JSON字符串反序列化
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}